import axios from "axios";
import router from '../router'
import storageUtil from '../utils/localstorage'
import Loading from 'element-plus/lib/components/loading'
import ElMessage from 'element-plus/lib/components/message'

let config = {
	baseURL: '',
	timeout: 10000
}
//创建实例
let instance = axios.create(config)
let loading = {};
//请求拦截器
instance.interceptors.request.use(config => {
	// console.log(req);
	let userId = storageUtil.get("userId");
	let token = storageUtil.get("token");
	if (userId) {
		config.headers.userId = userId;
		config.headers.token = token;
		// config.headers={"userId":userId,"token":token};
	}
	loading = Loading.service({
		fullscreen: true,
		text: "数据加载中..."
	}) //显示加载效果
	return config; //拦截器里一定要返回config, 不然请求无法发送出去。
})
//响应拦截器
instance.interceptors.response.use(resp => {
	loading.close();
	if (resp.status === 200) {
		let data = resp.data;
		if (data.code === 2) {
			// this.$message({
			// 	message: '您还没有登录',
			// 	type: 'error'
			// });
			//弹出框显示后台返回的错误信息
			ElMessage({
				showClose: true,
				message: data.msg,
				type: 'warning'
			});
			router.push("/login")
		} else if (data.code === 0) {
			return data.result;
		} else if (data.code === 4) {//密码错误次数太多， 请明天再试
			//弹出框显示后台返回的错误信息
			ElMessage({
				showClose: true,
				message: data.msg,
				type: 'warning'
			});
		} else {
			//弹出框显示后台返回的错误信息
			ElMessage({
				showClose: true,
				message: data.msg,
				type: 'warning'
			});
		}
	}
}, error => {
	//请求发生异常
	loading.close();
	return Promise.reject(error);
})

let http = {
	install(app) {
		app.config.globalProperties.$axios = instance;
	}
}
export default http;
